package Demo;

import java.util.PriorityQueue;
import java.util.TimerTask;

class MyTimerTask implements Comparable<MyTimerTask> {
    private final Runnable task;
    private final long time;

    public MyTimerTask(Runnable task, long delay) {
        this.task = task;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        task.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return Long.compare(this.time, o.time);
    }
}

class MyTimer {
    private final PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private final Object blocker = new Object();
    private volatile boolean shutdown = false;
    private Thread workerThread;

    public MyTimer() {
        workerThread = new Thread(() -> {
            while (!shutdown || !queue.isEmpty()) {  // 退出条件：关闭且队列空
                synchronized (blocker) {
                    try {
                        while (queue.isEmpty() && !shutdown) {
                            blocker.wait(); // 队列空且未关闭时等待
                        }
                        if (queue.isEmpty()) break; // 关闭且队列空时退出

                        MyTimerTask task = queue.peek();
                        long currentTime = System.currentTimeMillis();
                        long waitTime = task.getTime() - currentTime;

                        if (waitTime > 0) {
                            blocker.wait(waitTime); // 等待到任务时间
                        } else {
                            task.run();
                            queue.poll();
                        }
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        });
        workerThread.start();
    }

    public void schedule(TimerTask task, long delay) {
        synchronized (blocker) {
            if (shutdown) {
                throw new IllegalStateException("Timer is already shutdown");
            }
            queue.offer(new MyTimerTask(task, delay));
            blocker.notifyAll(); // 唤醒所有等待线程（避免假唤醒问题）
        }
    }

    public void shutdown() {
        synchronized (blocker) {
            shutdown = true;
            blocker.notifyAll(); // 强制唤醒线程检查关闭标志
        }
    }

    public void awaitTermination() throws InterruptedException {
        workerThread.join();
    }
}

public class Main3 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer = new MyTimer();

        // 添加定时任务
        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("1000ms Task");
            }
        }, 1000);

        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("2000ms Task");
            }
        }, 2000);

        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("3000ms Task");
            }
        }, 3000);

        // 关闭定时器并等待所有任务完成
        myTimer.shutdown();
        myTimer.awaitTermination();
        System.out.println("All tasks completed, exiting...");
    }
}